package com.leyou.gateway.filters;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private FilterProperties filterProp;

    @Override
    public String filterType() {
        // 登录拦截，使用前置过滤器
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        // 1.获取Request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 2.获取请求路径
        String path = request.getRequestURI();
        // 3.判断白名单
        boolean isAllowPath = false;
        for (String allowPathPrefix : filterProp.getAllowPaths()) {
            // 是否符合前缀
            if(StringUtils.startsWith(path, allowPathPrefix)){
                isAllowPath = true;
                break;
            }
        }
        // 返回true：run方法会执行。返回false：run方法不会执行
        return !isAllowPath;
    }

    @Override
    public Object run() throws ZuulException {
        // 1.获取Request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 2.获取请求cookie中的token
        String token = CookieUtils.getCookieValue(request, jwtProp.getUser().getCookieName());
        // 3.验证并解析token，获取到用户信息， 用到JWT工具，需要公钥
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);

            //	5，验证通过，拿到用户，
            UserInfo info = payload.getInfo();
            log.info("用户{}正在请求{}", info.getUsername(), request.getRequestURI());

            // TODO 继续做权限校验
        } catch (JwtException | IllegalArgumentException e) {
            log.error("IP {} 非法请求，地址：{}", request.getRemoteHost(), request.getRequestURI());
            //	4，验证不通过（未登录或超时，返回错误信息）
            ctx.setSendZuulResponse(false);
            // 返回错误码为401，代表为登录
            ctx.setResponseStatusCode(401);
        }
        return null;
    }
}
